/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.open.api.core.service.processor.base.pre;

import cn.hutool.core.lang.Assert;
import info.peigen.hotpot.business.customer.facade.info.partner.PartnerInfo;
import info.peigen.hotpot.business.customer.facade.order.partner.PartnerQueryOrder;
import info.peigen.hotpot.business.customer.facade.result.partner.PartnerQueryResult;
import info.peigen.hotpot.common.core.enums.YesOrNo;
import info.peigen.hotpot.component.open.api.core.config.OpenApiAuthVerifyIgnoreConfiguration;
import info.peigen.hotpot.component.open.api.core.exception.PartnerNotExistException;
import info.peigen.hotpot.component.open.api.core.service.processor.base.AbstractOpenApiServiceProcessor;
import info.peigen.hotpot.component.open.api.facade.order.OpenApiOrder;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessor;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessorServiceContext;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;


/**
 * <b>(OpenApiAuthVerifyProcessor)</b>
 * 校验接口是否有权限调用
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/6/13
 */
@SuppressWarnings("rawtypes")
@Component
public class OpenApiAuthVerifyProcessor extends AbstractOpenApiServiceProcessor implements OpenApiProcessor {
    @Inject
    OpenApiAuthVerifyIgnoreConfiguration openApiAuthVerifyIgnoreConfiguration;

    @Override
    public Integer level() {
        return 3;
    }

    @Override
    public void execute(OpenApiProcessorServiceContext serviceContext) {
        OpenApiOrder       order  = serviceContext.getOrder();
        PartnerQueryResult result = partnerQueryServiceFacade.queryPartnerInfo(PartnerQueryOrder.builder().partnerId(order.getPartnerId()).build());
        result.throwIfNotSuccess(PartnerNotExistException::new);
        PartnerInfo partnerInfo = result.getInfo();
        Assert.notNull(partnerInfo, UnsupportedOperationException::new);

        if (YesOrNo.Y.equals(partnerInfo.getPermission().getIsEnableValidation())) {
            Assert.isTrue(partnerInfo.getPermission().isEnableApiCode(order.getApiCode())
                    || openApiAuthVerifyIgnoreConfiguration.isIgnoreApiCodes(order.getApiCode()), () -> new UnsupportedOperationException("无api权限,apiCode=" + order.getApiCode()));
        }

        serviceContext.setPartnerInfo(partnerInfo);
    }
}